<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <!-- 设置唯一id  node-key="id"-->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>

          <el-button size="mini" @click="exportEmployee">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size=" mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDele(row.id)">
                <template v-slot:reference>
                  <el-button style="margin-left:10px" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="pageChange"
          />
        </el-row>
      </div>

    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 分配角色弹窗 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" @close="showRoleDialog = false">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOk">确定</el-button>

          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>

        </el-col>

      </el-row>

    </el-dialog>
  </div>

</template>

<script>
import { getDepartment } from '@/api/department'
import { assignRole, deleteEmployee, exportEmployee, getEmployeeDetail, getEmployeeList, getEnableRoleList } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      list: [],
      total: 0,
      showExcelDialog: false,
      showRoleDialog: false,
      roleList: [],
      roleIds: [],
      currentUserId: null // 用来记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 点击确认按钮
    async btnRoleOk() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('角色分配成功')
      this.showRoleDialog = false
    },
    // 员工分配角色
    async btnRole(id) {
      // 获取角色列表
      this.roleList = await getEnableRoleList()
      // 选择的id
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartment(), 0)
      // 初始化时,记录id
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // setCurrentKey 通过 key 设置某个节点的当前选中状态，使用此方法必须设置 node-key 属性
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.getEmployeeList()
      this.queryParams.page = 1
    },
    // 分页
    pageChange(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },
    // 输入框值改变
    changeValue() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出员工信息
    async exportEmployee() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const result = await exportEmployee()
      console.log('员工信息数据', result)
      loading.close()
      FileSaver.saveAs(result, '员工信息.xlsx')
    },
    // 删除员工
    async confirmDele(id) {
      await deleteEmployee(id)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.queryParams.page > 1) { this.queryParams.page-- }
      this.getEmployeeList()
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 50px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
